import React, { useState, useEffect, useRef } from 'react';
import { useRequest, useModel } from 'umi';
import { Row, Progress , Card, Tabs, Descriptions, Image, message,Collapse,Radio} from 'antd';
import { getMonitoringDevicInfo, getEChartsOption, getMonitoringPhase } from '@/services/deviceLive';
import { queryDeviceAlarm } from '@/services/deviceAlarm';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import moment from 'moment'
import ECharts from 'echarts-for-react';
import UpdateForm from '@/pages/alarm/record/components/UpdateForm';

import {transducerTripcode} from '@/utils/alarmcode-enum';
import moxing from '@/assets/dtype_mabao.png';
import Monitor from '../components/Monitoring';
import styles from './index.less';
const { TabPane } = Tabs;
import { updateDeviceAlarm } from '@/services/deviceAlarm';
import slg from '@/assets/img/img/slg2.png';
import item1 from '@/assets/img/img/2item1-1.png';

import item2 from '@/assets/img/img/item8.png';
import item3 from '@/assets/img/img/2item1-3-1.png';

import item4 from '@/assets/img/img/2item1-3-1.png';

import item6 from '@/assets/img/img/2item1-1.png';
import item5 from '@/assets/img/img/2item1-3-2.png';

/**
 * 更新节点
 * @param fields
 */
 const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceAlarm(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

const details: React.FC = (props: any) => {
  const { params } = props.match;
 
  const second = useRequest(() => {
    return getMonitoringPhase({...params,type:4});
  }, {
    pollingInterval: 3000,
    pollingWhenHidden: false
  });

  const [deviceInfo, setDeviceInfo] = useState<API.DeviceItem>({});
  const [runningData, setRunningData] = useState({});
  const [alarmSourceEnumDict, setAlarmSourceEnumDict] = useState({});
  const [alarmCategoryEnumDict, setAlarmCategoryEnumDict] = useState({});
  const [alarmLevelEnumDict, setAlarmLevelEnumDict] = useState({});
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [chartIndex, setChartIndex] = useState(1);

  const [onLineBackgroundColor, setOnLineBackgroundColor] = useState('#8ca1aa');
  const [alarmBackgroundColor, setAlarmBackgroundColor] = useState('red');


  const actionRef = useRef<ActionType>();

  const { initialState,setInitialState } = useModel('@@initialState');
  const { mySocket,dicts } = initialState || {};
  if (mySocket) {
    mySocket.send(params.id);
    mySocket.onmessage =async function (e) {
     // console.log(`onmessage: ${e.data}`);
      //排除心跳数据
      if ("heartbeat" != e.data&&e.data.indexOf("RunningData")!=-1) {
        onMessage(e);
      }else if ("heartbeat" != e.data&&e.data.indexOf("AlarmData")!=-1) {
        const data = JSON.parse(e.data);
        await setInitialState((s) => ({ ...s, alarmNotices: data.AlarmData }));
      }
    };
  }

  const onMessage = (e:any) => {
    const message = JSON.parse(e.data);
   // const runningData = {...message.RunningData, ...message.ReliabilityData}
    const rData = message.RunningData||{};
    if(rData.deviceId!=params.id){
      return;
     }
    rData.acquisitionTime = moment().format("YYYY-MM-DD HH:mm:ss");
    if(runningData?.online==0&&rData?.online==1){
       go();
    }
    if(runningData?.alarm==0&&rData?.alarm==1){
        go1();
    }
   
    setRunningData(rData);
  }


  useEffect(() => {
    const setSelectData = async () => {
      var details = await getMonitoringDevicInfo(params);
      if (details.deviceInfo) {
        details.deviceInfo.protocol = JSON.parse(details.deviceInfo.protocolConfig) || [];
      }
      setRunningData(details.runningData);
      setDeviceInfo(details.deviceInfo);
      if(details?.runningData?.online==1){
        await go();
      }
      if(details?.runningData?.trip==1){
        await  go1();
      }
   
    }
    setSelectData();
    if(dicts){
      setAlarmSourceEnumDict(dicts["5Enum"]);
      setAlarmCategoryEnumDict(dicts["6Enum"]);
      setAlarmLevelEnumDict(dicts["8Enum"])

    }
  }, []);

  const sleep = (t) => {
    return new Promise((res,rej)=>{
        setTimeout(res,t)
    })
}

  async function  go() {
    setOnLineBackgroundColor("yellow");
    await sleep(200)
    setOnLineBackgroundColor("#19377f");
    await  sleep(200)
    go()
}


async function  go1() {
  setAlarmBackgroundColor("red");
  await sleep(300)
  setAlarmBackgroundColor("#19377f");
  await  sleep(300)
  go1()
}

function  getJingDu() {
  let a=runningData?.closedLoopFeedback;
  let b=runningData?.closedLoopSetting;
 let c=a/b*100;

return c.toFixed(2);
}

let option = {
  // title: {
  //   text: '电能健康分析',
  //   left:'center',
  //   textStyle: {
  //     color: 'white'
  //   },
  // },
  // grid: {
  //   top: 50,
  //   left: 60,
  //   right: 50,
  //   bottom: 30
  // },
  radar: {
    // shape: 'circle',
    indicator: [
      { name: '电压', max: 6500 },
      { name: '频率', max: 16000 },
      { name: '功率因数', max: 30000 },
  
    ]
  },
  series: [
    {
      type: 'radar',
      data: [
        {value: [ runningData?.voltage||0 , runningData?.frequency||0, runningData?.powerFactor||0]}
      ]
    }
  ]
};


const option2 = {
   color: ["#40a9ff"],
   grid: {
     top: 50,
     left: 60,
     right: 50,
     bottom: 30
   },
   title: {
     text: '',
   },
   tooltip: {
     trigger: 'axis'
   },
   legend: {
     // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
     textStyle: {
       color: '#ddd',
     },
   },
   toolbox: {
     show: false,
   },
   xAxis: {
   
     type: 'category',
    
     data: second.data?.phaseTime,
     splitLine: {
       show: false,
       lineStyle: {
         type: 'dashed'
       }
     },
     axisLine: {
       lineStyle: {
         type: 'dashed',
         color: '#ddd',//左边线的颜色
       }
     },
   },
   yAxis: {
     type: 'value',
     scale:true,
     min:0,  //取0为最小刻度
     axisLabel: {
       formatter: '{value}'
     },
     minInterval:1,
     splitLine: {
       show: true,
       lineStyle: {
         type: 'dashed'
       }
     },
     axisLine: {
       lineStyle: {
         type: 'dashed',
         color: '#ddd',//左边线的颜色
       }
     },
   },
   series: second.data?.data
 };
  const option3 = {
    color: ["#40a9ff"],
    grid: {
      top: 50,
      left: 60,
      right: 50,
      bottom: 30
    },
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
      textStyle: {
        color: '#ddd',
      },
    },
    toolbox: {
      show: false,
    },
    xAxis: {
    
      type: 'category',
    
      data: second.data?.phaseTime,
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    yAxis: {
      type: 'value',
      scale:true,
      min:0,  //取0为最小刻度
      axisLabel: {
        formatter: '{value}'
      },
      minInterval:1,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    series: second.data?.data1
  };
 

  const columns: ProColumns[] = [

    {
      title: '报警时间',
      dataIndex: 'alarmTime',

    },
    {
      title: '报警类别',
      dataIndex: 'alarmType',
       valueEnum: alarmCategoryEnumDict
    },
    {
      title: '报警级别',
      dataIndex: 'alarmLevel',
      valueEnum:  alarmLevelEnumDict,
    },
    {
      title: '报警数值',
      dataIndex: 'alarmValue',
    }, {
      title: '信息来源',
      dataIndex: 'defectSource',
      valueEnum: alarmSourceEnumDict,
    },
    {
      title: '处置状态',
      dataIndex: 'state',
      valueEnum: {0:'未处置',1:'已处置'}
    },
    {
      title: '报警处置信息',
      dataIndex: 'alarmAnswer',

    },



    {
      title: '操作',
      dataIndex: 'state',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>
       {record.state==0?
        <a onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >处置</a>:null} 
        </>
      )
    },
  ];


  
  return (
    <div className={styles.main} key={1}>
   
     <div  className={styles.flexBetween} style={{    marginRight: '10px',    alignItems: 'end'}}>
     <div className={styles.flexBetween} style={{flex:5,    alignItems: 'end',minWidth:'650px',width: 'auto'}}>
        <div style={{flex:  1}}> 
          <div  className={styles.flex}>  
            <Image    src={slg}  preview={false} />
            <div className={styles.deviceInfo} >
                <div>
                  <span  className={styles.title} > {deviceInfo?.deviceName||'--'} </span>
                  <span className={styles.updateTimeText} > (最新同步时间：{runningData?.acquisitionTime||'--'})</span>
                </div>
                <div className={styles.flexBetween} > 
                  <div>  
                    <span>设备位号：{deviceInfo?.deviceNo||'--'} </span>  
                    <span>&nbsp;  安装位置：{deviceInfo?.areaName||'--'}{deviceInfo?.devicePosition}</span>
                  </div>
                  <div>最新维保日期:{deviceInfo?.latestMaintenanceTime}</div>
                </div>  
            </div>
          </div>
          </div>

      </div>
      <div  className={styles.flexBetween} style={{flex:3,justifyContent: 'end',marginLeft:'50px'}}>
        <div  className={ [styles.flexBetween, styles.stateR].join(' ')}>
          <div>
            <div  className={runningData?.close==1? [styles.yuan, styles.bgGreen].join(' '):styles.yuan} ></div>
            <span>合闸</span>
          </div>
          <div>
            <div  className={runningData?.trip==1? [styles.yuan, styles.bgRed].join(' '):styles.yuan} ></div>
            <span>故障</span>
          </div>
          <div>
            <div  className={runningData?.online==1? [styles.yuan, styles.bgYellow].join(' '):styles.yuan} style={{backgroundColor:onLineBackgroundColor}}></div>
            <span>通讯</span>
          </div>
        </div>
      </div>
     </div>
     <div  className={styles.flexBetween} style={{  margin:  '12px 0 30px 0', alignItems:'start'}}>
      <div  style={{flex:5}}>
        <div className={styles.flex} >
         <div  className={styles.dataItem} style={{    marginLeft: '0px'}}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item1}  preview={false} /> <span className={styles.topRight} >设定频率{runningData?.settingFrequency}Hz</span></div>

            <div style={{margin: '0 0 -2px 10px',color:'rgb(64 255 255)',    marginTop: '-3px'}}  className={styles.flex}><span><span  className={styles.nameItalic} >P</span></span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.totalActivePower}</span>千瓦时</div></div>
            <div className={styles.attribute}  >总有功电量</div>
          </div>
          <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item3}  preview={false} /> <span className={styles.topRight} ></span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.activePower}</span><span className={styles.unit}>瓦</span></div>
              <div className={styles.attribute}>有功功率</div>
            </div>
        
            <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item3}  preview={false} /> <span className={styles.topRight} ></span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.powerFactor}</span><span className={styles.unit}>%</span></div>
              <div className={styles.attribute}>功率因数cos</div>
            </div>
        </div>
        <div className={styles.flex} >
         <div  className={styles.dataItem} style={{    marginLeft: '0px'}}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item4}  preview={false} /> <span className={styles.topRight} >设定频率{runningData?.settingFrequency}Hz</span></div>

            <div style={{margin: '0 0 -2px 10px',color:'rgb(64 255 255)',    marginTop: '-3px'}}  className={styles.flex}><span><span  className={styles.nameItalic} >U</span></span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.voltage}</span>V</div></div>
            <div className={styles.attribute}  >电压</div>
          </div>
          <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item5}  preview={false} /> <span className={styles.topRight} ></span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.current}</span><span className={styles.unit}>A</span></div>
              <div className={styles.attribute}>电流</div>
            </div>
        
            <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item6}  preview={false} /> <span className={styles.topRight} ></span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.frequency}</span><span className={styles.unit}>Hz</span></div>
              <div className={styles.attribute}>频率</div>
            </div>
        </div>
       
     
      </div>
      <div style={{flex:3}}  className={ styles.alarmBox} >
         <span>电能健康分析</span>
         <ECharts     option={option}  style={{height:'250px',width:'285px',margin:'auto'}}/>
   
        
      </div>
      </div>
    
     
     <Row key={6}>
        <div className={styles.tabsTitle}>
          <a className={chartIndex!=1?styles.a1:[styles.a1,styles.tabcheck1].join(' ')}   onClick={()=>setChartIndex(1)} >有功电量趋势分析</a><div  className={chartIndex!=1?styles.a1after:[styles.a1after,styles.a1afterCheck].join(' ')}></div>
          <a className={chartIndex!=2?styles.a2:[styles.a2,styles.tabcheck].join(' ')}   onClick={()=>setChartIndex(2)}> 电流趋势分析</a>
          <a className={chartIndex!=3?styles.a3:[styles.a3,styles.tabcheck].join(' ')}  onClick={()=>setChartIndex(3)}> 报警记录</a>
        </div>
        <Card  className={ styles.modalItem} title={null} style={{width:"100%"}} >
          <ECharts  style={{display:chartIndex==1?'block':'none'}}   option={option2} />
          <ECharts  style={{display:chartIndex==2?'block':'none'}} option={option3} />
          <ProTable
            style={{display:chartIndex==3?'block':'none'}}
                  headerTitle=""
                  className={styles.alarmTable}
                  actionRef={actionRef}
                  rowKey="id"
                  search={false}
                  request={(tableParams) => queryDeviceAlarm({ ...tableParams, ...{ deviceId: params.id } })}
                  columns={columns}
                  options={false}
                  pagination={{
                    defaultCurrent: 1,
                    defaultPageSize: 10,
                  }}
              />
          </Card>
        
      </Row>
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
      
        />
      ) : null}
    </div>
  );
};

export default details;